package com.leyou.listener;

import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.config.SmsProperties;
import com.leyou.utils.SmsHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.leyou.common.constants.RocketMQConstants.CONSUMER.SMS_VERIFY_CODE_CONSUMER;
import static com.leyou.common.constants.RocketMQConstants.TAGS.VERIFY_CODE_TAGS;
import static com.leyou.common.constants.RocketMQConstants.TOPIC.SMS_TOPIC_NAME;

/**
 * @author: guojy
 * @date: 2020/3/15 11:05
 * @Description:
 * @version: 1.0
 */

@Component
@RocketMQMessageListener(topic = SMS_TOPIC_NAME,
        selectorExpression = VERIFY_CODE_TAGS,
        consumerGroup = SMS_VERIFY_CODE_CONSUMER)
public class SendMessageListener implements RocketMQListener<String> {
    @Autowired
    private SmsHelper smsHelper;
    @Autowired
    private SmsProperties prop;

    @Override
    public void onMessage(String message) {
        System.out.println("监听成功");
        // message 是一个map，包括手机号和验证码
        if (StringUtils.isBlank(message)) {
            return;
        }
        // 将 message转换为 map
        Map<String, String> map = JsonUtils.toMap(message, String.class, String.class);
        // 由于sendMessage 参数三 需要一个json格式  {"code":"45555"},所以需要把map中的电话去除
        String phoneNum = map.remove("phone");
        // 将剩下的map转为  json
        String code = JsonUtils.toString(map);
        System.out.println(code);
        if (StringUtils.isBlank(phoneNum)) {
            return;
        }
        // 发送消息
        try {
            smsHelper.sendMessage(phoneNum, prop.getSignName(), prop.getVerifyCodeTemplate(), code);
        } catch (LyException e) {
        }
    }
}
